I've noticed that my custom sorting option works perfectly when browsing the shop but fails in search results. The current code follows many examples available:
// Add "Sort by discount" to sorting options. Defaults to biggest to smallest discount.
add_filter('woocommerce_get_catalog_ordering_args'
,'mycode_woocommerce_add_salediscount_to_catalog_ordering_args'
);
function mycode_woocommerce_add_salediscount_to_catalog_ordering_args( $args ) {
$orderby_value = isset( $_GET['orderby'] )
? wc_clean( $_GET['orderby'] )
: apply_filters('woocommerce_default_catalog_orderby'
,get_option('woocommerce_default_catalog_orderby' )
);
if ( 'discount' == $orderby_value ) {
$args['orderby'] = 'meta_value_num';
$args['order'] = 'DESC';
$args['meta_key'] = 'discount_amount';
}
return $args;
}
add_filter('woocommerce_default_catalog_orderby_options'
,'mycode_woocommerce_add_salediscount_to_catalog_orderby'
);
add_filter('woocommerce_catalog_orderby'
,'mycode_woocommerce_add_salediscount_to_catalog_orderby'
);
function mycode_woocommerce_add_salediscount_to_catalog_orderby( $sortby ) {
$sortby['discount'] = __( 'Sort by discount', 'woocommerce' );
return $sortby;
}
This code I've added to the my_custom_code.php
which is a simple plugin for my own code.
It sorts based on a meta value that every product in my store has.
When used on a search results page, instead of the custom ordering, the ordering is the same as 'relevance'.
Looking through the WC code that controls ordering, I see that is_search()
is called in multiple places, with ordering reset to 'relevance' but the default sorting options are able to override this and they still work (e.g. sort by price still works).
So I imagine that I need to adjust the code slightly to behave in the same way as the default search options but I can't see how to do this.
Does anyone know?
Thanks!